﻿using System;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;

namespace UnityEditor.UI
{    
    delegate void DrawSpriteDelegate(Sprite sprite, Rect drawArea, Color color);
    public delegate void OnPreviewGUI(Rect rect, GUIStyle background);
    public class DynamicAtlasPreviewGUI
    {
        private Sprite atlasSprite = null;
        private bool preview = false;
        private DrawSpriteDelegate DrawSprite;
        private string atlasName = "";

        public DynamicAtlasPreviewGUI(Sprite atlas)
        {
            atlasSprite = atlas;
            atlasName = atlas.name;
        }

        public DynamicAtlasPreviewGUI(Texture2D atlas)
        {
            if (atlas)
            {
                atlasSprite = Sprite.Create(atlas, new Rect(0, 0,atlas.width, atlas.height), new Vector2(0, 0));
                atlasName = atlas.name;
            }
        }

        public void OnEnable()
        {
            DrawSprite = typeof(UnityEditor.UI.ImageEditor).Assembly.GetType("UnityEditor.UI.SpriteDrawUtility")
                .GetMethod("DrawSprite",new Type[]
                {
                    typeof(Sprite), typeof(Rect), typeof(Color)
                },new ParameterModifier[]
                {
                    new ParameterModifier(3)
                }).CreateDelegate(typeof(DrawSpriteDelegate)) as DrawSpriteDelegate;
        }

        public void OnInspectorGUI(DynamicAtlasGroup group)
        {
            GUILayout.BeginHorizontal();
            GUILayout.Label("Atlas");
            preview = GUILayout.Toggle(preview, "Preview");
            if (GUILayout.Button("Show DynamicAtlas"))
            {
                DynamicAtlasWindow.ShowWindow( group);
            }
            GUILayout.EndHorizontal();
            GUILayout.Label(atlasName);
        }

        public void OnPreviewGUI(OnPreviewGUI raw,Rect rect, GUIStyle background,Color c)
        {
            if (preview)
            {
                if ((UnityEngine.Object) atlasSprite == (UnityEngine.Object) null)
                    return;
                DrawSprite(atlasSprite, rect, c);
            }
            else raw?.Invoke(rect,background);
        }
    }
}